<?php

namespace web\api\controller;

use Elliptic\Curve\ShortCurve\Point;

/**
 * Description of News
 * 提现
 */
class Withdrawal extends UserBase {

    /**
     * 提现列表
     */
    public function withdrawalList() {
        $m = new \addons\order\model\Without();
        $list = $m->getDataList($this->getPageIndex(),$this->getPageSize(), 'user_id = '. $this->user_id, '*', 'status asc,add_time asc');
        return $this->successJSON($list);
    }

    /**
     * 提现手续费
     */
    public function withoutTax(){
        $accountM = new \addons\member\model\MemberAccountModel();
        $level = $accountM->where('id',$this->user_id)->value('level');
        $data['is_operation'] = 0;
        $data['fee'] = 0;
        $data['gx_amount'] = 0;
        if($level > 0){
            $data['is_operation'] = 1;
            $level_data =(new \addons\member\model\LevelConfig())->where(['level' => $level])->find();
            $amount = $this->_post('amount');
            $data['fee'] = round(($amount * $level_data['poundage_rate'] / 100), 2);
            $data['gx_amount'] = $amount;
            $sysParameterM = new \web\common\model\sys\SysParameterModel;
            $price = $sysParameterM->getValByName('kof_price');
            $data['gx_amount'] = $amount * $price;
        }
        return $this->successJSON($data);
    }

    /**
     * 提现
     * @return array|mixed
     */
    public function doWithout() {
        $sys_data = (new \web\common\model\sys\SysParameterModel)->getParameterDataByKey(11);
        $time = explode('-', $sys_data['without_time']);
        $hour = date('H');
        $start = trim($time[0]);
        $end = trim($time[1]);
        if($start>$hour){
            return $this->failJSON('提现开始时间为'.$start.'点');
        }
        if($end<$hour){
            return $this->failJSON('提现结束时间为'.$end.'点');
        }

        $user_id = $this->user_id;

        $accountM = new \addons\member\model\MemberAccountModel();
        $pay_password = $this->getParamVal('pay_password');
        $user_data = $accountM->checkPayPwdLevel($user_id,$pay_password);
        if(empty($user_data)) return $this->failJSON('交易密码错误');
        $amount = $this->getParamVal('amount');
        $withdrawal_address = $this->getParamVal('withdrawal_address');
        if(floor($amount) != $amount){
            return $this->failJSON('提现金额必须为整数');
        }
        if($amount < $sys_data['without_min']) return $this->failJSON('提现最低金额为：'.$sys_data['without_min']);

        $verify_code = $this->getParamVal('verify_code');
        $verifyM = new \addons\member\model\VericodeModel();
        $_verify = $verifyM->VerifyCode($verify_code, $user_data['phone'], 6, $user_data['country_code']);
        if (empty($_verify)) {
            return $this->failJSON(lang('MEMBER_CODE_WRONG'));
        }

        $level = $accountM->where('id', $user_id)->value('level');
        $is_operation = 0;
        $fee = 0;
        $gx_amount = 0;
        $remark = '';
        $levelConfigM = new \addons\member\model\LevelConfig();
        if($level > 0){
            $is_operation = 1;
            $level_data = $levelConfigM->where(['level' => $level])->find();
            $fee = round(($amount * $level_data['poundage_rate'] / 100), 2);
            $remark = ',手续费'.$fee;
            $price = (new \web\common\model\sys\SysParameterModel)->getValByName('dc_price');
            $gx_amount = $amount * $price;
        }

        if($is_operation == 0){
            return $this->failJSON('等级过低，无法提现');
        }

        $total_amount = $amount + $fee;
        $balanceM = new \addons\member\model\Balance();

        $kof_balance_type = self::KOF_TYPE;
        $gx_balance_type = self::GX_TYPE;

        $kof_balance = $balanceM->getBalanceAmountByType($user_id, $kof_balance_type);
        $gx_balance = $balanceM->getBalanceAmountByType($user_id, $gx_balance_type);

        if($kof_balance < $total_amount) return $this->failJSON('余额不足');
        if($gx_balance < $gx_amount) return $this->failJSON('贡献值余额不足，请到商城消费或做任务看广告获得!');
        try {
            $balanceM->startTrans();
            //减少用户余额---提现金额
            $re_balance = $balanceM->updateBalance($user_id, $kof_balance_type, $total_amount, false);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('扣款失败，请稍后再试');
            }

            $recordM = new \addons\member\model\TradingRecord();
            $re_record = $recordM->addRecord($user_id, $total_amount, $re_balance['before_amount'], $re_balance['amount'], $kof_balance_type, 5, 0, 0, '提现'.$remark);
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('扣款流水失败，请稍后再试');
            }

            //扣除贡献值
            $re_balance = $balanceM->updateBalance($user_id, $gx_balance_type, $gx_amount, false);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('贡献值扣款失败，请稍后再试');
            }
            $re_record = $recordM->addRecord($user_id, $gx_amount, $re_balance['before_amount'], $re_balance['amount'], $gx_balance_type, 5, 0, 0, '提现 扣除贡献值');
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('贡献值扣款流水失败，请稍后再试');
            }

            $add_data = [
                'user_id' => $this->user_id,
                'ref_no' => $this->createOrderSn('tx'),
                'coin_type' => $kof_balance_type,
                'amount' => $amount,
                'gx_amount' => $gx_amount,
                'withdrawal_address' => $withdrawal_address,
                'add_time' => NOW_DATETIME,
                'rate' => $fee,
                'record_id' => $re_record,
            ];

            $withoutM = new \addons\order\model\Without();
            $res = $withoutM->add($add_data);
            if(!$res){
                $balanceM->rollback();
                return $this->failJSON('提交订单失败，请稍后再试');
            }
            $balanceM->commit();
            return $this->successJSON();
        } catch (\Exception $ex) {
            $balanceM->rollback();
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 生成随机订单号
     * @param string $sn
     * @return string
     */
    public function createOrderSn($sn = '') {
        return $sn.date('YmdHis') . rand(10000, 99999);
    }

}